<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ServiceController
 *
 * @author nmthong
 */
class MobileController extends Controller{
    // Members
    /**
     * Key which has to be in HTTP USERNAME and PASSWORD headers 
     */
    Const APPLICATION_ID = 'ASCCPE';
 
    Const KEY_SERVICE = 'ordersystem';
    Const NUM_ENCRYPTION=3;
    /**
     * Default response format
     * either 'json' or 'xml'
     */
    private $format = 'json';
    /**
     * @return array action filters
     */   
    
        public function actionLogin(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                $query="SELECT * FROM os_users where username=:username";
                $command=$connection->createCommand($query);
                $command->bindParam(':username',$json->username,PDO::PARAM_STR);
                $dataReader=$command->query();
                if(($row=$dataReader->read())!==false && $row['password']==$json->password) {
                    $data=array("user"=>$row);
                    $result=array('data'=>$data,'status'=>'ok');
                    $string=json_encode($result);
                    echo $string;
                }else{
                $result=array('data'=>'','status'=>'fail','error'=>'login fail');
                 echo $string=json_encode($result);                    
                }

            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);

             }   
             
           
        }    
    
        public function actionGetCategory(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                $query="SELECT * FROM os_category where sale_id=".$json->sale_id;
                $command=$connection->createCommand($query);
                $dataReader=$command->query();
                $rows_category = array();

                while(($row=$dataReader->read())!==false) {
                    $rows_category[]=$row;

                }
                $data=array("categories"=>$rows_category);
                $result=array('data'=>$data,'status'=>'ok');
                $string=json_encode($result);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);

             }            
        }
               
        public function actionGetItems(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                $query="SELECT * FROM os_item WHERE IdCategory=".$json->category_id;
                $command=$connection->createCommand($query);
                $dataReader=$command->query();
                $rows_item = array();

                while(($row=$dataReader->read())!==false) {
                    $rows_item[]=$row;

                }
                $data=array("items"=>$rows_item);
                $result=array('data'=>$data,'status'=>'ok');
                $string=json_encode($result);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
            }            
        }   
        
        public function actionGetStores(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                $query="SELECT * FROM os_store where sale_id=".$json->sale_id;;
                $command=$connection->createCommand($query);
                $dataReader=$command->query();
                $rows_item = array();

                while(($row=$dataReader->read())!==false) {
                    $rows_item[]=$row;
                }
                $data=array("stores"=>$rows_item);
                $result=array('data'=>$data,'status'=>'ok');
                $string=json_encode($result);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
            }            
        }
        
        public function actionGetNews(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                $query="SELECT * FROM os_news where sale_id=".$json->sale_id; ;
                $command=$connection->createCommand($query);
                $dataReader=$command->query();
                $rows_item = array();

                while(($row=$dataReader->read())!==false) {
                    $rows_item[]=$row;
                }
                $data=array("news"=>$rows_item);
                $result=array('data'=>$data,'status'=>'ok');
                $string=json_encode($result);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
            }            
        }          
        
        public function actionInsertOrder()
        {
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                $current_time=time();
                if(strcmp($json->discount_code,"")!=0){
                    $sql="SELECT discount_percent FROM os_discount WHERE discount_code=".$json->discount_code." and discount_start<".$current_time." and discount_end>".$current_time." and sale_id=".$json->sale_id;
                    $command=$connection->createCommand($sql);
                    $dataReader=$command->query();
                    if(($row=$dataReader->read())!==false) {
                        $json->discount=$json->sum_price*(intval($row)/100);
                    }               
                }
                $sql="CALL SP_INS_ORDER(:sale_id,:name_order,:name_customer,:mobile_customer,:date_order,:discount,:sum_price,:description,:is_finish,@out)";                 
           
                $command=$connection->createCommand($sql);
                $command->bindParam(':sale_id',$json->sale_id,PDO::PARAM_INT);
                $command->bindParam(':name_order',$json->name_order,PDO::PARAM_STR);
                $command->bindParam(':name_customer',$json->name_customer,PDO::PARAM_STR);
                $command->bindParam(':mobile_customer',$json->mobile_customer,PDO::PARAM_STR);
                $command->bindParam(':date_order',$json->date_order,PDO::PARAM_STR);

                $command->bindParam(':discount',$json->discount,PDO::PARAM_STR);                
                $command->bindParam(':sum_price',$json->sum_price,PDO::PARAM_STR);
                $command->bindParam(':description',$json->description,PDO::PARAM_STR);
                $command->bindParam(':is_finish',$json->is_finish,PDO::PARAM_INT);
                $row_count=$command->execute();
                $data = $connection->createCommand("select @out as result;")->queryScalar();
                $json->order_id=$data + 0;
                //insert  items
                $array_orderitems=$json->array_items;
                foreach ($array_orderitems as &$value) {
                    $sql="CALL SP_INS_ORDERITEM(:sale_id,:order_id,:item_id,:price,:name_item,:number_item,:discount)";                 
                    $command=$connection->createCommand($sql);
                    $command->bindParam(":sale_id",$value->sale_id,PDO::PARAM_INT);
                    $command->bindParam(":order_id",$data,PDO::PARAM_STR);
                    $command->bindParam(":item_id",$value->Id,PDO::PARAM_INT);
                    $command->bindParam(":price",$value->Price,PDO::PARAM_STR);
                    $command->bindParam(":name_item",$value->NameItem,PDO::PARAM_STR);
                    $command->bindParam(":number_item",$value->NumberOrder,PDO::PARAM_INT);
                    $command->bindParam(":discount",$value->Discount,PDO::PARAM_STR);                
                    $row_count=$command->execute();
            
                }
                $resul=array('data'=>$json,'status'=>'ok');
                $string=json_encode($resul);
                echo $string;
            }catch(Exception $e){
                $resul=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($resul);
            }
                           

        }        
 
         public function actionUploadImage(){
            try{
                if ($_FILES["file"]["error"] > 0) {
                  $result=array('data'=>'','status'=>'fail','error'=>$_FILES["file"]["error"]);
                  $string=json_encode($result);                
                } else {
                        $file = $_FILES ['file'];
                        $name = $file ['name'];
                        $type = $file ['type'];
                        $size = $file ['size'];
                        $tmppath = $file ['tmp_name']; 
                        if($name!="")
                        {
                            $name=$_POST['data']."_".$name;
                            if(move_uploaded_file ($tmppath, 'files/'.$name))//image is a folder in which you will save image
                            {
                                    
                                    $resul=array('data'=>array('file'=>$name),'status'=>'ok');
                                    $string=json_encode($resul);
                            }else{
                                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                                $string=json_encode($result);                               
                            }
                        }else{
                                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                                $string=json_encode($result);                             
                        }
                }
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
             }            
        }        
 
         public function actionInsertGeneral(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $command = Yii::app()->db->createCommand();
                $command->insert($json->table, $json->data);
                $row_count=$command->execute();
                $id=$connection->getLastInsertID();
                $resul=array('data'=>$id,'status'=>'ok');
                $string=json_encode($resul);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
             }            
        }
        
         public function actionUpdateGeneral(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $command = Yii::app()->db->createCommand();
                $command->update($json->table,$json->data,$json->id.'=:id', array(':id'=>$json->value_id));
                $row_count=$command->execute();
                $resul=array('data'=>$row_count,'status'=>'ok');
                $string=json_encode($resul);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
             }            
        }
        
         public function actionDeleteGeneral(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $command = Yii::app()->db->createCommand();
                $command->delete($json->table,$json->id.'=:id', array(':id'=>$json->value_id));
                $row_count=$command->execute();
                $resul=array('data'=>$row_count,'status'=>'ok');
                $string=json_encode($resul);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
             }            
        } 
        
         public function actionSelectShops(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $command = Yii::app()->db->createCommand();
                $row=$command->select('*')->from('os_salepoint')->where('sale_business=:sale_business', array(':sale_business'=>$json->type_business))->limit($json->limit,$json->offset)->queryAll(); 
                $data=array('shops'=>$row);
                $resul=array('data'=>$data,'status'=>'ok');
                $string=json_encode($resul);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
             }       
             return;
        }        
        
         public function actionSelectGeneral(){
            try{
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $command = Yii::app()->db->createCommand();
                $row=$command->select('*')->from($json->table)->where('sale_id=:sale_id', array(':sale_id'=>$json->sale_id))->queryAll(); 
                $data=array($json->table=>$row);
                $resul=array('data'=>$data,'status'=>'ok');
                $string=json_encode($resul);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
             }       
             return;
        }        
        
        public function actionGetToken(){
             try{
                $encrypt=new PITEncrypt();
                $post = Yii::app()->request->rawBody;
                $json=json_decode($post);
                $token='ordersystem'.'_'.time();
                $token=$encrypt->encrypt($token,3);               
                $result=array('data'=>$token,'status'=>'ok');
                $string=json_encode($result);
                echo $string;
            }catch(Exception $e){
                $result=array('data'=>'','status'=>'fail','error'=>$e->getMessage());
                 echo $string=json_encode($result);
             }            
        }
}

?>
